<template>
  <el-form
    ref="forgotPwd"
    :model="passwordForm"
    class="forgot-pwd-form"
    label-width="110px"
    label-position="right"
    :rules="rules">
    <el-form-item label="账号" prop="email">
      <el-input
        v-model="passwordForm.email"
        size="small"
        auto-complete="off"
        placeholder="请输入邮箱">
      </el-input>
    </el-form-item>
    <el-form-item label="验证码" prop="code">
      <el-input
        v-model="passwordForm.code"
        size="small"
        placeholder="请输入验证码">
      </el-input>
      <el-button :disabled="countdown > 0" class="obtain-code" @click="handleCode">
        <!-- 显示倒计时或获取验证码 -->
        {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
      </el-button>
    </el-form-item>
    <el-form-item label="新密码" prop="password">
      <template #label>
        <span>新密码</span>&nbsp;
        <el-tooltip content="密码必须同时包含大小写英文和数字，长度:8-64" placement="top">
          <i class="iconfont icon-wenhao"></i>
        </el-tooltip>
      </template>
      <input type="password" style="display: none;" autocomplete="new-password">
      <el-input
        v-model="passwordForm.password"
        :type="passwordType"
        size="small"
        auto-complete="off"
        placeholder="请设置登录密码">
        <i slot="suffix" class="el-icon-view el-input__icon" @click="showPassword" />
      </el-input>
    </el-form-item>
    <el-form-item label="确认新密码" prop="confirmPassword">
      <el-input
        v-model="passwordForm.confirmPassword"
        :type="confirmPassword"
        size="small"
        auto-complete="off"
        placeholder="请再次输入设置登录密码">
        <i slot="suffix" class="el-icon-view el-input__icon" @click="showConfirmPassword" />
      </el-input>
    </el-form-item>
    <el-form-item v-if="website.validateCode" prop="code">
      <Verify
        ref="verify"
        :mode="'pop'"
        :captcha-type="'blockPuzzle'"
        :img-size="{ width: '330px', height: '155px' }"
        @success="verifySuccess" />
    </el-form-item>
    <el-button type="primary" size="small" class="login-submit" @click="handleLogin">找回密码
    </el-button>
    <div class="login-tips">已有账号？<span class="jump-login" @click="jumpLogin">去登录</span></div>
  </el-form>
</template>
<script>
import { emailCode, modifyPassword } from '@/api/admin/user'
import { Base64 } from 'js-base64'
import { mapGetters } from 'vuex'
import Verify from '@/components/verifition/Verify'
export default {
  name: 'forgotPassword',
  components: {
    Verify
  },
  data() {
    return {
      passwordForm: {
        email: '', // 邮箱
        code: '', // 验证码
        password: '', // 密码
        confirmPassword: '' // 确认密码
      },
      passwordType: 'password',
      confirmPassword: 'password',
      rules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: this.validateEmail, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请设置登录密码', trigger: 'blur' },
          { min: 8, max: 64, message: '请输入规范的密码', trigger: 'blur' },
          { validator: this.validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入设置登录密码', trigger: 'blur' },
          { min: 8, max: 64, message: '请输入规范的密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      },
      countdown: 0, // 倒计时秒数
      initialCountdown: 60, // 倒计时初始值，根据需要可以调整这个值
      verifycode: '' // 图形验证码
    }
  },
  computed: {
    ...mapGetters(['website'])
  },
  methods: {
    // 邮箱校验
    validateEmail(rule, value, callback) {
      const flag = new RegExp(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/).test(value)
      if (!flag) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    },
    // 密码校验
    validatePassword(rule, value, callback) {
      // if (this.addPassFormData.confirmPassword !== '' && value !== this.addPassFormData.confirmPassword) {
      //   callback(new Error("两次输入的密码不一致"))
      // } else {
      //   callback()
      // }
      const flag = new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z0-9!@#$%^&*()\-_=+[\]{}|\\:;"'<>,.?/~`]+$/).test(value)
      if (!flag) {
        callback(new Error('请输入规范的密码'))
      } else {
        callback()
      }
    },
    // 确认密码校验
    validateConfirmPassword(rule, value, callback) {
      if (value === this.passwordForm.password) {
        callback()
      } else {
        callback(new Error("两次输入的密码不一致"))
      }
      const flag = new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z0-9!@#$%^&*()\-_=+[\]{}|\\:;"'<>,.?/~`]+$/).test(value)
      if (!flag) {
        callback(new Error('请输入规范的密码'))
      } else {
        callback()
      }
    },
    showPassword() {
      this.passwordType === ''
        ? (this.passwordType = 'password')
        : (this.passwordType = '')
    },
    showConfirmPassword() {
      this.confirmPassword === ''
        ? (this.confirmPassword = 'password')
        : (this.confirmPassword = '')
    },
    // 获取图形验证
    handleCode() {
      this.$refs.forgotPwd.validateField('email', (errorMsg) => {
        if (errorMsg) {
          // errorMsg 将会是你在 rules 中设定的消息，这里我们不需要做额外的事情
        } else {
          // 如果验证通过，那么执行获取验证码的逻辑
          this.$refs.verify.show()
        }
      })
    },
    verifySuccess(params) {
      this.verifycode = params.captchaVerification
      this.handleObtainCode()
    },
    // 跳转至登录页
    jumpLogin() {
      this.$emit('change', 'user')
      this.$refs['forgotPwd'].resetFields()
    },
    // 获取邮箱验证码
    handleObtainCode() {
      const params = {
        email: this.passwordForm.email,
        type: 'password'
      }
      emailCode(params).then(res => {
        // 假设以下是 API 调用成功后的回调部分
        this.$message.success('验证码发送成功')
        this.countdown = this.initialCountdown // 初始化倒计时
        const intervalId = setInterval(() => {
          if (this.countdown > 0) {
            this.countdown -= 1 // 减少倒计时
          } else {
            clearInterval(intervalId) // 清除定时器
          }
        }, 1000) // 每1000毫秒（1秒）执行一次
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    handleLogin() {
      this.$refs.forgotPwd.validate(valid => {
        if (valid) {
          const params = {
            username: this.passwordForm.email,
            code: this.passwordForm.code,
            password: Base64.encode(this.passwordForm.password)
          }
          modifyPassword(params).then(res => {
            this.$message.success('密码找回成功!')
            this.$store.commit('SET_ACCESS_TOKEN', res.data.data.access_token)
            this.$store.commit('SET_REFRESH_TOKEN', res.data.data.refresh_token)

            setTimeout(() => {
              this.$router.push({ path: '/wel' })
            }, 100)
          }).catch(err => {
            this.$message.error(err.message)
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.obtain-code {
  border: 0 !important;
  background: transparent !important;
  border-left: 1px solid #DCDFE6 !important;
  padding-left: 10px;
  right: 0;
  &.is-disabled {
    color: #C0C4CC !important;
  }
}
.login-tips {
  color: #333;
  margin-top: 20px;

  .jump-login {
    color: #275FE8;
    font-size: 14px;
    cursor: pointer;
  }
}

::v-deep .el-form-item .el-form-item__content .mask + .el-form-item__error {
  display: none !important;
}
</style>
